package com.xiang.WebSocket;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiang.api.Util;
import com.xiang.api.entity.FrontDataPage;
import com.xiang.api.entity.Message;
import com.xiang.sql.StaticService;
import com.xiang.sql.entity.User;

public class RecvManage {
  MyWebSocket ws;
  /** 缓存大小 1M */
  final int cacheSize = 1024 * 1024;

  public RecvManage(MyWebSocket ws) {
    this.ws = ws;
    ws.send(new Message(ws.user, "me"));
  }

  @SuppressWarnings("unchecked")
  public Object recv(String message) {
    Message msg = null;
    try {
      msg = JSONObject.parseObject(message, Message.class);
    } catch (Exception e) {
    }
    if (msg == null) {
      return null;
    }
    if (msg.type.equals("test")) {
      return Util.zip(message);
    }
    msg.md5 = null;
    boolean isMd5 = msg.sid != null && msg.sid.indexOf('_') == 0, setNull = true;
    Method method = null;
    try {
      method = RecvManage.class.getMethod(msg.type, JSONObject.class);
    } catch (NoSuchMethodException | SecurityException e) {
    }
    Object mif = this;
    if (method == null) {
      List<String> ts = Util.splitByUpperCase(msg.type);
      int tl = ts.size(), size = tl;
      Field field = null;
      while (--tl > 0) {
        String tableMethodName = Util.FristLower(String.join("", ts.subList(tl, size))),
            tableName = Util.FristLower(String.join("", ts.subList(0, tl)));
        try {
          field = StaticService.class.getField(tableName);
        } catch (Exception e) {
          continue;
        }
        try {
          mif = field.get(null);
          if (mif != null) {
            method = mif.getClass().getMethod(tableMethodName, JSONObject.class, User.class);
            setNull = isMd5 && !tableMethodName.equals("read");
            break;
          }
        } catch (Exception e) {
          break;
        }
      }
    }
    if (method == null) {
      msg.message = "type错误:" + msg.type;
      msg.data = null;
    } else {
      try {
        if (setNull) {
          msg.data = null;
        } else {
          msg.data = method.invoke(mif, msg.data == null ? new JSONObject() : msg.data, ws.user);
          if (msg.data instanceof Page) {
            msg.data = new FrontDataPage((Page<Object>) msg.data);
          }
          String sd = Util.toJString(msg.data), md5 = Util.toHash(sd, false);
          if (isMd5) {
            msg.data = sd.length() > cacheSize ? md5 : null;
          } else if (sd.length() > cacheSize) {
            msg.md5 = md5;
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        msg.message = Util.errString(e);
        msg.data = null;
      }
    }
    return msg;
  }
}
